﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Globalization;
using NPOI.SS.Formula.Functions;
using System.Data;
using ET_DbCommon.Model;
using ET_DbCommon.DAL;
using ET_DbCommon.Enum;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// TestQuestionEdit.xaml 的交互逻辑
    /// </summary>
    public partial class TestQuestionEdit : Window, INotifyPropertyChanged
    {
       public TestQuestionViewModel viewModel { get; set; }

        public ObservableCollection<TestPaperViewModel> PaperList { get; set; }
        public ObservableCollection<TestQuestionViewModel> QuestionList { get; set; }
        public bool IsLook { get; set; }
        public ObservableCollection<TestPaperInfoViewModel> PaperInfoList { get; set; } = new ObservableCollection<TestPaperInfoViewModel>();//Add by gy
        public ObservableCollection<MinusPointsParameter> MinusPointsParameterList { get; set; } = new ObservableCollection<MinusPointsParameter>();
        public List<DeviceModel> StationList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.车站];
        public List<DeviceModel> TrainList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.列车];

        public List<SceneFileModel> SceneFileList = new List<SceneFileModel>();

        public string loadname="";//指示初加载的场景文件名
        public List<QuestionIdNameModel> questionIdNames = new List<QuestionIdNameModel>();
        #region MinusPointsType
        private Dictionary<int, string> m_MinusPointsType;

        public Dictionary<int, string> MinusPointsType
        {
            get
            {
                return this.m_MinusPointsType;
            }
            set
            {
                this.m_MinusPointsType = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region INotifyPropertyChanged 接口实现
        
            public event PropertyChangedEventHandler PropertyChanged;
            public void OnPropertyChanged([CallerMemberName] string propName = null)
            {
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
            }

        #endregion
        private TestPaperInfoViewModel m_SelectedTestPaperInfo;

        public TestPaperInfoViewModel SelectedTestPaperInfo
        {
            get
            {
                return this.m_SelectedTestPaperInfo;
            }
            set
            {
                this.m_SelectedTestPaperInfo = value;
                this.OnPropertyChanged();
            }
        }
        public class TestPaperInfoViewModel:NotifyPropertyChanged
        {
            public int Id { get; set; }
            public int TestPaperId { get; set; }
            private int m_OldOrderNumber;
            public int OldOrderNumber
            {
                get { return m_OldOrderNumber; }
                set 
                { 
                    this.m_OldOrderNumber = value;
                    this.OnPropertyChanged();
                }
            }
            private int m_NewOrderNumber;
            public int NewOrderNumber
            {
                get { return m_NewOrderNumber; }
                set
                {
                    this.m_NewOrderNumber = value;
                    this.OnPropertyChanged();
                }
            }
            private int m_TrainId;
            public int TrainId
            {
                get { return m_TrainId; }
                set
                {
                    this.m_TrainId = value;
                    this.OnPropertyChanged();
                }
            }
            private string m_Branch;
            public string Branch
            {
                get { return m_Branch; }
                set
                {
                    this.m_Branch = value;
                    this.OnPropertyChanged();
                }
            }          

        }
        public TestQuestionEdit(TestQuestionViewModel _viewModel, ObservableCollection<TestPaperViewModel> _PaperList, ObservableCollection<TestQuestionViewModel> _questionList, bool _isLook = false)
        {
            InitializeComponent();
            this.viewModel = _viewModel;
            this.PaperList = _PaperList;
            this.QuestionList = _questionList;
            this.IsLook = _isLook;
        }

        public List<postModel> roleModels { get; set; } = PostDAL.GetPostInfo();
        public List<DeviceModel> MyStationList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.车站];//获取所有车站 Add by gy
        public List<DeviceModel> AreaList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.计轴区段];
        public List<DeviceModel> MyAreaList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.计轴区段];
       
        public TestQuestionEdit()
        {
            InitializeComponent();
        }
        //保存
        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(cmbRole.Text))
            {
                if (cmbRole.Text.Contains(","))
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in cmbRole.Text.Split(','))
                    {
                        sb.Append(roleModels.FirstOrDefault(t => t.post_name == item).post_id).Append(",");
                    }
                    viewModel.Roles = sb.ToString().TrimEnd(','); 
                }
                else
                {
                    viewModel.Roles= roleModels.FirstOrDefault(t => t.post_name == cmbRole.Text).post_id;
                }
              
            }

            if (!string.IsNullOrWhiteSpace(viewModel.AttachQuestion) && this.viewModel.IsMain== "false")
            {
                MessageBox.Show("副场景不能设置关联副场景！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                this.viewModel.IsMain = "true";
                
                return;
            }
            Dictionary<int, string> dicMinusPoints = new Dictionary<int, string>();
            foreach (var param in this.MinusPointsParameterList)
            {
                dicMinusPoints.Add(param.MinusPointsID, param.Score + "|" + param.ExceptionTrains);
            }
            if (viewModel.Id == 0)
            {
                Paper_TestQuestionDAL.Insert(viewModel.Model, out int newId);
                viewModel.MinusPoints = JsonConvert.SerializeObject(dicMinusPoints);
                if (newId> 0 )
                {
                    viewModel.Id = newId;
                    this.DialogResult = true;
                }
            }
            else
            {
                if (this.viewModel.IsMain== "false" && this.QuestionList.FirstOrDefault(p => p.AttachQuestion != null && p.AttachQuestion.Split(',').Contains(this.viewModel.Id.ToString())) != null)
                {
                    MessageBox.Show("当前场景作为其他主场景的副场景，无法修改为主场景！");
                    this.viewModel.IsMain = "false";
                    return;
                }
                if (this.viewModel.IsMain== "true" && this.PaperList.FirstOrDefault(p => p.TestQuestions.FirstOrDefault(x => x.Id == this.viewModel.Id) != null) != null)
                {
                    if (Paper_TestQuestionDAL.Update(viewModel.Model) > 0)
                    {
                        this.DialogResult = true;
                    }
                    this.viewModel.IsMain = "false";
                    return;
                }
                viewModel.MinusPoints = JsonConvert.SerializeObject(dicMinusPoints);
                if (this.filePath.SelectedValue != null)
                {
                    viewModel.SceneFileName = SceneFileList.Find(o => o.Id == (int)this.filePath.SelectedValue).SceneFileName;
                    viewModel.SceneFile = SceneFileList.Find(o => o.Id == (int)this.filePath.SelectedValue).Id;
                }

                if (this.DefaultStation.SelectedValue != null && this.DefaultStation.SelectedValue is int)
                {
                    viewModel.StationID = (int)this.DefaultStation.SelectedValue;
                }



                if (Paper_TestQuestionDAL.Update(viewModel.Model) > 0)
                {
                    this.DialogResult = true;
                }
            }
            if (this.filePath.Text != "未上传")
            {
                if (this.filePath.SelectedValue != null)
                {
                    if (SceneFileList.Find(o => o.Id == (int)this.filePath.SelectedValue).SceneFileName != loadname)
                    {
                        viewModel.SceneFile = SceneFileList.Find(o => o.Id == (int)this.filePath.SelectedValue).Id;
                        viewModel.SceneFileName = SceneFileList.Find(o => o.Id == (int)this.filePath.SelectedValue).SceneFileName;
                        //应用的场景变更
                        SceneFileModel nowmodel = new SceneFileModel();
                        nowmodel = this.SceneFileList.Find(s => s.SceneFileName == viewModel.SceneFileName);
                        List<string> nowlist = new List<string>();
                        if (nowmodel != null)
                        {
                            questionIdNames.Clear();
                            questionIdNames = Paper_TestQuestionDAL.GetQuestionIdNames();
                            if (string.IsNullOrEmpty(nowmodel.UsedQuestions) || nowmodel.UsedQuestions == "#")
                            {
                                nowmodel.UsedQuestions = "#" + this.questionIdNames.Find(p => p.Id == this.viewModel.Id).TestName;
                            }
                            else
                            {
                                nowlist = new List<string>(nowmodel.UsedQuestions.Split('#'));
                                nowlist.Add(this.questionIdNames.Find(p => p.Id == this.viewModel.Id).TestName);
                                nowmodel.UsedQuestions = String.Join("#", nowlist.ToArray());
                            }
                        }
                        //if (nowlist != null)
                        //{
                        //    SceneFileDAL.Update(nowmodel);
                        //}
                    }
                }
               
            }
            
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
      
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = this;
            if (!string.IsNullOrEmpty(viewModel.Roles))
            {
                StringBuilder sb = new StringBuilder();
                var role = viewModel.Roles.Split(',');
                foreach (var item in role)
                {
                    sb.Append(roleModels.FirstOrDefault(t => t.post_id == item).post_name).Append(",");
                }
                viewModel.RoleName = sb.ToString().TrimEnd(',');
            }
            questionIdNames.Clear();
            questionIdNames = Paper_TestQuestionDAL.GetQuestionIdNames();
            this.MinusPointsParameterList.Clear();
            this.PaperInfoList.Clear();
            if (this.IsLook)
                JudgeIsLook(this.LayOut);

            if(viewModel.SceneFileName!=null)
            {
                loadname = viewModel.SceneFileName;
            }
            SceneFileList = SceneFileDAL.GetAllIgnoreFile();
            this.filePath.ItemsSource = SceneFileList;
            this.DefaultStation.ItemsSource = StationList;

            this.DataContext = this;

            viewModel.SceneFileName = SceneFileList.Find(x => x.Id == viewModel.SceneFile)?.SceneFileName;


            if (this.viewModel.SceneFileName!=null&&this.viewModel.SceneFile!=null)
            {
                try
                {
                    this.filePath.SelectedItem = SceneFileList.First(p => p.SceneFileName == this.viewModel.SceneFileName);
                }
                catch(Exception exc)
                {

                }
            }
            else 
            {
                this.filePath.Text = this.viewModel.SceneFileUpload;
            }



            //北京科研修改副场景添加方法
            this.cmbAssistantQuestions.ItemsSource = Paper_TestQuestionDAL.GetAll().ToList().FindAll(T=>T.IsMain== "1" && T.TestName != null);
            //this.cmbAssistantQuestions.ItemsSource = this.QuestionList.ToList().FindAll(p => p.TestQuestionID != this.viewModel.TestQuestionID && !p.IsMain); ;

            this.cmbRole.ItemsSource = PostDAL.GetPostInfo();

        }

        public static void JudgeIsLook(Grid LayOut)
        {
            foreach (var child in LayOut.Children)
            {
                if (child is StackPanel)
                    (child as StackPanel).Visibility = Visibility.Collapsed;
                if (child is TextBox)
                    (child as TextBox).IsReadOnly = true;
                if (child is ComboBox)
                    (child as ComboBox).IsEnabled = false;
                if (child is CheckBox)
                    (child as CheckBox).IsEnabled = false;
                if (child is DataGrid)
                    (child as DataGrid).IsEnabled = false;
                if (child is GroupBox)
                    JudgeIsLook((child as GroupBox).Content as Grid);
            }
        }

        private void Choose_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = "场景文件 (*.scene)|*.scene";
            if (openDlg.ShowDialog() != true) return;

            this.filePath.Text = openDlg.FileName;
            this.viewModel.SceneFileName = openDlg.SafeFileName;
            
        }

        private void BtnMinusPoints_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.MinusPointsParameterList.Add(new MinusPointsParameter());
                    break;
                case "删除":
                    var para = dgMinusPoints.SelectedItem as MinusPointsParameter;
                    if (para != null)
                    {
                        this.MinusPointsParameterList.Remove(para);
                    }
                    break;
            }
        }

        private void CmbMinusPointsType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox combox = sender as ComboBox;
            ContentPresenter cp = (sender as ComboBox).TemplatedParent as ContentPresenter;
            if (cp != null)
            {
                MinusPointsParameter parameter = cp.Content as MinusPointsParameter;
                var dev = (KeyValuePair<int, string>)combox.SelectedItem;
                parameter.MinusPointsName = dev.Value;
            }
        }

        private void cmbStationID_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //筛选逻辑区段 Add by gy
            if (cmbStationID.SelectedItem != null)
            {            
                MyAreaList = AreaList;
                DeviceModel selectedItem = (DeviceModel)cmbStationID.SelectedItem;
                var area = AreaList.Where((T => T.DeviceName.Contains(selectedItem.DeviceName.ToString()))).ToList();
                MyAreaList = area;
                this.cmbAreaID.ItemsSource = MyAreaList;
            }
            //MyAreaList = AreaList;
            //MyAreaList = MyAreaList.Where((T => T.DevName.Contains(MyStationList[Convert.ToInt32(cmbStationID.SelectedValue) - 1].DevName.ToString()))).ToList();
            
        }

        private void AddManage_Click(object sender, RoutedEventArgs e)
        {
            if ((OrderNumber.Text != "" || DownOrderNumber.Text != "") && cmbAreaID.Text != "" && FaultType.Text != "")
            {
                string LogicID = AreaList.Where(p => p.DeviceName == cmbAreaID.Text).FirstOrDefault().DeviceId.ToString();
                //TestPaperManageDAL.InsertExamData(viewModel.Id, viewModel.Describes, FaultType.Text.ToString(), Convert.ToInt32(LogicID), Convert.ToInt32(OrderNumber.Text), Convert.ToInt32(DownOrderNumber.Text));
                //cmbStationID.SelectedItem = null;
                this.Window_Loaded(null, null);
            }
            else
            {
                MessageBox.Show("请检查输入内容");
            }
        }

        private void AddInfo_Click(object sender, RoutedEventArgs e)
        {
            if ((OldOrderNumber.Text != "" || NewOrderNumber.Text != "") && TrainID.Text != "" && Branch.Text != "") 
            {
                //TestPaperInfoDAL.InsertExamInfo(viewModel.Id, Convert.ToInt32(OldOrderNumber.Text), Convert.ToInt32(NewOrderNumber.Text), Convert.ToInt32(TrainID.Text), Branch.Text.ToString());
                this.PaperInfoList.Clear();
                this.Window_Loaded(null, null);
            }
        }
        //设置textbox只能输入数字 Add by gy
        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            bool shiftKey = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;//判断shift键是否按下
            if (shiftKey == true)//当按下shift
            {
                e.Handled = true;//不可输入
            }
            else//未按shift
            {
                if (!((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Delete || e.Key == Key.Back || e.Key == Key.Tab || e.Key == Key.Enter))
                {
                    e.Handled = true;//不可输入
                }
            }
        }

        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            Edit.Visibility=Visibility.Collapsed;
            Canceledit.Visibility = Visibility.Visible;
            AddInfo.Visibility = Visibility.Visible;
            UpdateInfo.Visibility = Visibility.Visible;
            DeleteInfo.Visibility = Visibility.Visible;
        }

        private void Canceledit_Click(object sender, RoutedEventArgs e)
        {
            Edit.Visibility = Visibility.Visible;
            Canceledit.Visibility = Visibility.Collapsed;
            AddInfo.Visibility = Visibility.Collapsed;
            UpdateInfo.Visibility = Visibility.Collapsed;
            DeleteInfo.Visibility= Visibility.Collapsed;
        }

        private void dgGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(this.SelectedTestPaperInfo!=null)
            {
                this.OldOrderNumber.Text = SelectedTestPaperInfo.OldOrderNumber.ToString();
                this.NewOrderNumber.Text = SelectedTestPaperInfo.NewOrderNumber.ToString();
                this.Branch.Text = SelectedTestPaperInfo.Branch.ToString();
                this.TrainID.Text = SelectedTestPaperInfo.TrainId.ToString();
            }
        }

        private void UpdateInfo_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedTestPaperInfo!=null)
            {
                //TestPaperInfoDAL.UpdateExamInfo(this.SelectedTestPaperInfo.Id,viewModel.Id, Convert.ToInt32(OldOrderNumber.Text), Convert.ToInt32(NewOrderNumber.Text), Convert.ToInt32(TrainID.Text), Branch.Text.ToString());
                this.PaperInfoList.Clear();
                this.Window_Loaded(null, null);
            }
        }

        private void DeleteInfo_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedTestPaperInfo != null)
            {
                //TestPaperInfoDAL.DeleteExamInfo(SelectedTestPaperInfo.Id);
                this.PaperInfoList.Clear();
                this.Window_Loaded(null, null);
            }
        }

        private void DeleteManage_Click(object sender, RoutedEventArgs e)
        {
            //TestPaperManageDAL.DeleteExamInfo(this.viewModel.Id);
            this.Window_Loaded(null, null);
        }
        bool sign = true;
        private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (scrollbar == null)
                return;
            double num = Math.Abs((int)(e.Delta / 2));
            double offset = 0.0;
            if (e.Delta > 0)
            {
                sign = false;
                offset = Math.Max((double)0.0, (double)(scrollbar.VerticalOffset - num));
            }
            else
                offset = Math.Min(scrollbar.ScrollableHeight, scrollbar.VerticalOffset + num);
            if (offset != scrollbar.VerticalOffset)
            {
                scrollbar.ScrollToVerticalOffset(offset);
                e.Handled = true;
            }
        }

        private void UpdateManage_Click(object sender, RoutedEventArgs e)
        {
            if ((OrderNumber.Text != "" || DownOrderNumber.Text != "") && cmbAreaID.Text != "" && FaultType.Text != "")
            {
                string LogicID = AreaList.Where(p => p.DeviceName == cmbAreaID.Text).FirstOrDefault().DeviceId.ToString();
                //TestPaperManageDAL.UpdateExamData(viewModel.Id, FaultType.Text.ToString(), Convert.ToInt32(LogicID), Convert.ToInt32(OrderNumber.Text), Convert.ToInt32(DownOrderNumber.Text));
                //cmbStationID.SelectedItem = null;
                this.Window_Loaded(null, null);
            }
            else
            {
                MessageBox.Show("请检查输入内容");
            }
        }
    }
    public class MinusPointsParameter : NotifyPropertyChanged
        {
            private int m_MinusPointsID;
            public int MinusPointsID
            {
                get
                {
                    return this.m_MinusPointsID;
                }
                set
                {
                    this.m_MinusPointsID = value;
                    this.OnPropertyChanged();
                }
            }

            private string m_MinusPointsName;
            public string MinusPointsName
            {
                get
                {
                    return this.m_MinusPointsName;
                }
                set
                {
                    this.m_MinusPointsName = value;
                    this.OnPropertyChanged();
                }
            }

            private string m_ExceptionTrains;
            public string ExceptionTrains
            {
                get
                {
                    return this.m_ExceptionTrains;
                }
                set
                {
                    this.m_ExceptionTrains = value;
                    this.OnPropertyChanged();
                }
            }

            private decimal m_Score;
            public decimal Score
            {
                get
                {
                    return this.m_Score;
                }
                set
                {
                    this.m_Score = value;
                    this.OnPropertyChanged();
                }
            }
        }

        //public class MinusPointsTypeVisibleConverter : IValueConverter
        //{
        //    public bool Reverse { get; set; }
        //    //public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        //    //{
        //    //    if (Reverse)
        //    //        return (MinusPointsType)value == DBCommon.Enum.MinusPointsType.停运 ? Visibility.Collapsed : Visibility.Visible;
        //    //    else
        //    //        return (MinusPointsType)value == DBCommon.Enum.MinusPointsType.停运 ? Visibility.Visible : Visibility.Collapsed;
        //    //}

        //    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        //    {
        //        throw new NotImplementedException();
        //    }
        //}
}

